<template>
  <div class="login-page">
    <!-- 左侧企业文化区 -->
    <div class="login-left">
      <!-- 背景图片，等你上传后替换src -->
      <img class="culture-bg-img" src="../../image/WechatIMG66.jpg" alt="企业文化背景" />
      <!-- <div class="culture-content">
        <div class="culture-row">
          <div class="culture-item value">
            <div class="culture-title">企业价值观</div>
            <div class="culture-desc">拥抱变化 大胆创新<br />认真工作 快乐生活</div>
          </div>
          <div class="culture-item mission">
            <div class="culture-title">企业使命</div>
            <div class="culture-desc">让世界<br />永葆童心</div>
          </div>
        </div>
        <div class="culture-row">
          <div class="culture-item logo">
      
            <img src="" alt="逸藩饰品" class="yifan-logo-img" />
            <div class="logo-text">逸藩饰品</div>
          </div>
          <div class="culture-item vision">
            <div class="culture-title">企业愿景</div>
            <div class="culture-desc">成为全球知名<br />儿童产品标杆</div>
          </div>
        </div>
        <div class="culture-footer">
          <div>中国逸藩</div>
          <div>世界扬帆</div>
        </div>
        <div class="company-bg-text">Jiangsu Yifan Accessories Co.,Ltd</div>
      </div> -->
   
    </div>
    <!-- 右侧登录表单区 -->
    <div class="login-right">
      <div class="login-form-container">
        <h2 class="login-title">逸藩数字化管理系统</h2>
        <!-- <div class="login-account-label">登录账号</div> -->
        <!-- 保持原有登录表单和逻辑不变 -->
        <el-form ref="loginFromRef" class="login-form" :model="loginForm" :rules="loginRules">
          <div class="title-container">
            <!-- <h3 class="title" style="margin-bottom: 10px;">欢迎使用</h3> -->
          </div>

          <!-- 企业号输入框，前端写死为1000，禁用状态 -->
          <el-form-item class="form-item-inline">
            <span class="icon-container">
              <svg style="width: 1em; height: 1em;" viewBox="0 0 1024 1024"><path fill="#bfbfbf" d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.9 0-372-166.1-372-372S306.1 140 512 140s372 166.1 372 372-166.1 372-372 372z"/><path fill="#bfbfbf" d="M512 256a64 64 0 1 0 0 128 64 64 0 0 0 0-128zm0 384c-70.7 0-128-57.3-128-128h64c0 35.3 28.7 64 64 64s64-28.7 64-64h64c0 70.7-57.3 128-128 128z"/></svg>
            </span>
            <el-input
              v-model="loginForm.company_code"
              placeholder="请输入企业代码"
              name="company_code"
              type="text"
              class="input-inline"
              disabled
            />
          </el-form-item>

          <el-form-item prop="username" class="form-item-inline">
            <span class="icon-container">
              <UserFilled style="width: 1em;height: 1em" />
            </span>
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              @keyup.enter.native="handleLogin"
              class="input-inline"
            />
          </el-form-item>

          <el-form-item prop="password" class="form-item-inline">
            <span class="icon-container">
              <Lock style="width: 1em;height: 1em" />
            </span>
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              name="password"
              :type="passwordType"
              @keyup.enter.native="handleLogin"
              class="input-inline"
            />
            <span class="show-pwd">
              <svg-icon :icon="passwordType === 'password' ? 'eye' : 'eye-open'" @click="onChangePwdType" />
            </span>
          </el-form-item>

          <!-- 勾选框和忘记密码按钮 -->
          <div class="login-btn-row">
            <el-checkbox v-model="loginForm.remember" @change="handleRememberPwd" class="remember-checkbox">记住密码</el-checkbox>
            <el-button type="text" size="small" @click="handleForgotPwd" style="margin-left: auto;">忘记密码？</el-button>
          </div>

          <el-button
            type="primary" style=" margin-bottom: 30px;width: 100%;" :loading="loading"
            size="large" @click.native.prevent="handleLogin"
          >
            <span>{{!loading ? '登 录' : '登 录 中...'}}</span>
          </el-button>
          <slot />
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.el-form-item__content{
    flex-direction: row;
}
.login-page {
  display: flex;
  height: 100vh;
}
.login-left {
  flex: 1.2;
  background: #eaf6ff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}
.culture-bg-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;
  filter: brightness(0.95);
}
.culture-content {
  width: 480px;
  margin: 0 auto;
  margin-top: 60px;
  position: relative;
  z-index: 1;
}
.culture-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}
.culture-item {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 2px 16px rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  position: relative;
}
.culture-item.logo {
  background: #fff;
  box-shadow: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.yifan-logo-img {
  width: 90px;
  margin-bottom: 8px;
}
.logo-text {
  font-size: 18px;
  color: #666;
  font-weight: bold;
  letter-spacing: 2px;
}
.culture-title {
  font-size: 20px;
  color: #409eff;
  font-weight: bold;
  margin-bottom: 8px;
}
.culture-desc {
  color: #333;
  font-size: 16px;
  text-align: center;
  line-height: 1.5;
}
.culture-item.value { background: #6ec6ff; color: #fff; }
.culture-item.mission { background: #7ed957; color: #fff; }
.culture-item.vision { background: #ffb84d; color: #fff; }
.culture-footer {
  position: absolute;
  left: 60px;
  bottom: 40px;
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  letter-spacing: 2px;
  line-height: 1.5;
  z-index: 2;
}
.company-bg-text {
  position: absolute;
  left: 60px;
  bottom: 10px;
  color: #fff;
  font-size: 16px;
  opacity: 0.7;
  z-index: 2;
}
.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}
.login-form-container {
  padding: 40px 30px;
  background: #fff;
  border-radius: 8px;
  min-width: 400px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  position: relative;
}
.login-title {
  text-align: center;
  margin-bottom: 62px;
  color: #409eff;
  font-size: 38px;
  font-weight: bold;
  letter-spacing: 2px;
}
.login-account-label {
  position: absolute;
  left: -90px;
  top: 60px;
  background: #fff;
  color: #409eff;
  font-size: 20px;
  font-weight: bold;
  border-radius: 0 20px 20px 0;
  padding: 10px 30px 10px 10px;
  box-shadow: 2px 2px 8px rgba(64,158,255,0.08);
  z-index: 2;
  writing-mode: vertical-lr;
  text-align: center;
  letter-spacing: 2px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.form-item-inline {
  display: flex !important;
  flex-direction: row;
  align-items: center;
  margin-bottom: 24px;
}
.input-inline {
  flex: 1;
  margin-left: 8px;
}
.icon-container {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #bfbfbf;
  font-size: 18px;
  margin-right: 4px;
}
.show-pwd {
  margin-left: 8px;
  cursor: pointer;
  user-select: none;
  font-size: 16px;
  color: #889aa4;
  display: flex;
  align-items: center;
}
.login-btn-row {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 18px;
}
.remember-checkbox {
  margin-right: auto;
  font-size: 14px;
}
</style>

<script setup>
import { UserFilled, Lock, Tickets } from "@element-plus/icons";

import { ref, onMounted } from "vue";
import { validatePassword, validateCode } from "./rules";
import { getCode } from "@/api/api";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

// 雪花效果
const snow = ref([]);
for (let i = 0; i < 1000; i++) {
	snow.value.push(i);
}

const codeNet = ref("");

onMounted(() => {
	getCodeImg();
  // 自动填充记住的账号密码
  const remember = localStorage.getItem('remember');
  if (remember === 'true') {
    const username = localStorage.getItem('remember_username') || '';
    const password = localStorage.getItem('remember_password') || '';
    loginForm.value.username = username;
    loginForm.value.password = password;
    loginForm.value.remember = true;
  }
});

// 数据源
const loginForm = ref({
	username: "",
	password: "",
	captcha_code: "",
	code_key: "",
	company_code: "1000",
	remember: false
});
// 验证规则
const loginRules = ref({
	username: [
		{
			required: true,
			trigger: "blur",
			message: "请输入用户名"
		}

	],
	password: [
		{
			required: true,
			trigger: "blur",
			validator: validatePassword()
		}

	],
	captcha_code: [
		{
			required: true,
			trigger: "blur",
			validator: validateCode()
		}

	]
});

// 处理密码框文本显示状态
const passwordType = ref("password");
const onChangePwdType = () => {
	if (passwordType.value === "password") {
		passwordType.value = "text";
	} else {
		passwordType.value = "password";
	}
};

// 登录动作处理
const loading = ref(false);
const loginFromRef = ref(null);
const store = useStore();
const router = useRouter();

/**
 * 登录
 */
const handleLogin = () => {
	loginFromRef.value.validate(valid => {
		if (!valid) return;
		console.log(loginForm.value);
		loading.value = true;
    // 登录前如果勾选了记住密码，保存一次
    if (loginForm.value.remember) {
      localStorage.setItem('remember', 'true');
      localStorage.setItem('remember_username', loginForm.value.username);
      localStorage.setItem('remember_password', loginForm.value.password);
    }
		store.dispatch("user/login", loginForm.value)
			.then((res) => {
				loading.value = false;
				// 兼容 code=200 的结构
        console.log("登录结果", res.code);
				if (res && (res.code == 200 || (res.status && res.status.error_code == 0))) {
          // 新增：保存后端返回的关键信息到 localStorage
          // 假设后端返回结构为 res.data 或 res（根据实际结构调整）
          const data = res.data || res;
          if (data) {
            // 你可以根据实际返回结构调整字段名
            localStorage.setItem('Cookie', data.Cookie || '');
            localStorage.setItem('Token', data.Token || '');
            localStorage.setItem('fid', data.fid || '');
            localStorage.setItem('员工ID', data['员工ID'] || '');
            localStorage.setItem('员工姓名', data['员工姓名'] || '');
            localStorage.setItem('员工编号', data['员工编号'] || '');
            localStorage.setItem('登录账号', data['登录账号'] || '');
            // 直接打印整个 data
            console.log('登录信息:', data);
          }
					router.push("/");
				} else {
					ElMessage.error((res && (res.msg || res.status?.error_msg)) || "登录失败");
				}
			})
			.catch(() => {
				loading.value = false;
			});
	});
};
/**
 * 获取图形验证码
 */
const getCodeImg = () => {
	getCode({})
		.then(data => {
			const obj = data.obj;

			loginForm.value.code_key = obj.code_key;
			codeNet.value = obj.code;
		})
		.catch(() => {
		});
};

const handleRememberPwd = (val) => {
  if (val) {
    localStorage.setItem('remember', 'true');
    localStorage.setItem('remember_username', loginForm.value.username);
    localStorage.setItem('remember_password', loginForm.value.password);
  } else {
    localStorage.removeItem('remember');
    localStorage.removeItem('remember_username');
    localStorage.removeItem('remember_password');
  }
};

const handleForgotPwd = () => {
  ElMessageBox.alert('请联系管理员重制密码', '忘记密码', {
    confirmButtonText: '确定',
    type: 'warning',
  });
};
</script>